const express_ws = require('express-ws');
const axios = require("axios");

const wsObj = {};
let currentApp = null

// 创建websocket服务器
const createWebsocketServer = function(app){
    currentApp = app
    express_ws(app);
    app.ws('/socketServer/wms', (ws, req) => {
        const uid = req.query.uid;
        if(!uid) {
            return ws.close();
        }
        wsObj[uid] = ws;
        websocketShowUser()
        ws.onmessage = (msg) => {
            let { toId, data, action} = JSON.parse(msg.data);
            const fromId = uid;
            if (toId && fromId != toId && wsObj[toId]) {
                // wsObj[toId]   表示 接收方 与服务器的那条连接
                // wsObj[fromId] 表示 发送方 与服务器的那条连接
                wsObj[toId].send(JSON.stringify( { fromId, data } ))
            }else{
                _handleAction(action,data,uid)
            }
        }
        ws.onclose = () => {
            delete wsObj[uid];
            websocketShowUser()
        }
    });
}

const _handleAction = function(action, data, uid){
    switch (action){
        case 'ITEMSTART_FROM_CLIENT':
            axios.post('http://localhost:8095/xunfei/sowManage/updateWorkingSowTask',{
                "sowTaskItemId":data.sowTaskItemId
            }).then(res=>{
                console.log('更新当前正在执行任务成功')
            }).catch(err=>{
                console.log('更新当前正在执行任务失败')
            })
            break;
        case 'ITEMFINISH_FROM_CLIENT':
            axios.post('http://localhost:8095/xunfei/sowManage/complete',{
                "sowTaskItemId": data.sowTaskItemId,
                "unitTotalCount": data.unitTotalCount,
                "time": data.time
            }).then(res=>{
                console.log('更新任务项完成数量完成')
            }).catch(err=>{
                console.log('更新任务项完成数量失败')
            })
            break;
        case 'ITEMSURECANCEL_FROM_CLIENT':
            axios.delete('http://localhost:8095/xunfei/sowManage/removeWaitingSowTask').then(res=>{
                console.log('删除等待分拣的所有任务成功')
            }).catch(err=>{
                console.log('删除等待分拣的所有任务失败')
            })
            break;
        case 'CURRENTCOUNTS_FROM_CLIENT':
            websocketBroadcastWithoutSelf(JSON.stringify({
                action,
                data
            }), uid)
            break;
        case 'LACKWARNING_FROM_CLIENT':
            websocketBroadcastWithoutSelf(JSON.stringify({
                action,
                data
            }), uid)
            break;
        default:
            console.log('未知的action：', action)
            break;
    }
}

// 广播
const websocketBroadcast = function(stringData){
    for(let i in wsObj){
        try {
            wsObj[i].send(stringData)
        }catch (e){
            console.log(e)
        }
    }
}

// 广播,除了自己
const websocketBroadcastWithoutSelf = function(stringData, selfName){
    for(let i in wsObj){
        if(i == selfName) continue;
        try {
            wsObj[i].send(stringData)
        }catch (e){
            console.log(e)
        }
    }
}

// 展示当前用户
const websocketShowUser = function(){
    console.log('当前websocket在线人数：', Object.keys(wsObj).length)
    console.log(Object.keys(wsObj))
}

module.exports = {
    createWebsocketServer,
    websocketBroadcast
}
